package net.cassite.daf4j.resource;

import java.io.IOException;
import java.io.InputStream;

/**
 * buffer for a resource
 */
public class Buffer extends InputStream {
        private InputStream inputStream;

        private InputStreamProvider iProvider;

        public Buffer(InputStreamProvider iProvider) {
                this.iProvider = iProvider;
        }

        public Buffer(InputStream stream) {
                this.inputStream = stream;
        }

        /**
         * retrieve the input stream of a resource
         *
         * @return input stream
         */
        public InputStream getInputStream() {
                if (inputStream == null) {
                        inputStream = iProvider.get();
                }
                return inputStream;
        }

        public void refresh() throws IOException {
                close();
                inputStream = iProvider.get();
        }

        @Override
        public int read() throws IOException {
                return getInputStream().read();
        }

        @Override
        public void close() throws IOException {
                if (inputStream != null) {
                        inputStream.close();
                }
        }
}
